package com.example.bilibili_miaosha.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.bilibili_miaosha.entity.User;
import com.example.bilibili_miaosha.service.IUserService;
import com.example.bilibili_miaosha.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName LoginInterceptor
 * @Description 自己的登录拦截器，太简陋了需要根据教程资料进行改善
 * @Author 川
 * @Date 2022/3/30 23:34
 * @Version 1.0
 **/

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入预拦截了！");
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        //进行登录验证的
        if (StringUtils.isEmpty(ticket)){//如果没有登录直接跳转到登录界面
            return false;
        }
        System.out.println("ticket:"+ticket);
//        User user = (User) session.getAttribute(ticket);//从session中拿到这个用户（原始版本的cookies登录方法）
//        System.out.println(request);  //显示被拦截的请求的地址
//        System.out.println(response);
        try {
//            User user = (User) redisTemplate.opsForValue().get("user:" + ticket);
            User user = userService.getUserByCookie(ticket,request,response);
            //这里没有接收到user， 提示为空变量异常， 两种方法都是空指针异常  最大的可能是这些方法为空    已经修改过来了
            System.out.println("user:"+user);
            if (user == null) {
                return false;
            }
        }catch (Exception e) {
            System.out.println(e);
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
